package com.wang.springbootinit.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.stream.CollectorUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wang.springbootinit.common.DeleteRequest;
import com.wang.springbootinit.common.ErrorCode;
import com.wang.springbootinit.constant.CommonConstant;
import com.wang.springbootinit.constant.UserConstant;
import com.wang.springbootinit.exception.BusinessException;
import com.wang.springbootinit.exception.ThrowUtils;
import com.wang.springbootinit.mapper.ChartMapper;
import com.wang.springbootinit.model.dto.chart.ChartAddRequest;
import com.wang.springbootinit.model.dto.chart.ChartEditRequest;
import com.wang.springbootinit.model.dto.chart.ChartQueryRequest;
import com.wang.springbootinit.model.dto.chart.ChartUpdateRequest;
import com.wang.springbootinit.model.entity.Chart;
import com.wang.springbootinit.model.entity.User;
import com.wang.springbootinit.model.vo.ChartInfoVO;
import com.wang.springbootinit.model.vo.ChartVO;
import com.wang.springbootinit.service.ChartService;
import com.wang.springbootinit.service.UserService;
import com.wang.springbootinit.utils.ChartQueryWrapperUtils;
import com.wang.springbootinit.utils.ConvertUtil;
import com.wang.springbootinit.utils.SqlUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.sql.Array;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 胡歌的腿毛
 * @description 针对表【chart(图表信息表)】的数据库操作Service实现
 * @createDate 2023-07-02 15:27:57
 */
@Service
public class ChartServiceImpl extends ServiceImpl<ChartMapper, Chart>
        implements ChartService {
    @Resource
    private UserService userService;


    /**
     * 创建图表信息
     *
     * @param chartAddRequest
     * @param request
     * @return
     */
    @Override
    public Long addChart(ChartAddRequest chartAddRequest, HttpServletRequest request) {
        Chart chart = new Chart();
        BeanUtils.copyProperties(chartAddRequest, chart);
        User loginUser = userService.getLoginUser(request);
        chart.setUserId(loginUser.getId());
        boolean result = this.save(chart);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        long newChartId = chart.getId();

        return newChartId;
    }


    /**
     * 根据id删除图表分析信息
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @Override
    public Boolean deleteChart(DeleteRequest deleteRequest, HttpServletRequest request) {
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        Chart oldChart = this.getById(id);
        ThrowUtils.throwIf(oldChart == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldChart.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        return this.removeById(id);
    }


    /**
     * 更新图表分析信息
     *
     * @param chartUpdateRequest 可选分析参数
     * @return
     */
    @Override
    public Boolean updateChart(ChartUpdateRequest chartUpdateRequest) {
        Chart chart = new Chart();
        BeanUtils.copyProperties(chartUpdateRequest, chart);
        long id = chartUpdateRequest.getId();
        // 判断是否存在
        Chart oldChart = this.getById(id);
        ThrowUtils.throwIf(oldChart == null, ErrorCode.NOT_FOUND_ERROR);
        boolean result = this.updateById(chart);
        return result;
    }

    /**
     * 根据图表id获取图表信息
     *
     * @param id
     * @param request
     * @return
     */
    @Override
    public ChartVO getChartById(long id, HttpServletRequest request) {
        Chart chart = this.getById(id);
        if (chart == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        ChartVO chartStatusVO = new ChartVO();
        BeanUtils.copyProperties(chart, chartStatusVO);
        chartStatusVO.setUser(ConvertUtil.UserVOConvert(loginUser));
        return chartStatusVO;
    }

    /**
     * 模糊查询  图表展示列表 模糊查询图表信息
     *
     * @param chartQueryRequest
     * @param request
     * @return
     */
    @Override
    public Page<Chart> searchListChartByPage(ChartQueryRequest chartQueryRequest, HttpServletRequest request) {
        long current = chartQueryRequest.getCurrent();
        long size = chartQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);

        QueryWrapper<Chart> queryWrapper = new QueryWrapper<>();
        Long id = chartQueryRequest.getId();
        String name = chartQueryRequest.getName();
        String goal = chartQueryRequest.getGoal();
        String chartType = chartQueryRequest.getChartType();
        Long userId = chartQueryRequest.getUserId();
        String sortField = chartQueryRequest.getSortField();
        String sortOrder = chartQueryRequest.getSortOrder();

        //模糊查询
        queryWrapper.eq(id != null && id > 0, "id", id);
        User user = userService.getUser(request);
        if(!user.getUserRole().equals(UserConstant.ADMIN_ROLE)){
            //普通用户
            queryWrapper.eq(ObjectUtils.isNotEmpty( user.getId()), "userId", user.getId());
        }

        queryWrapper.eq("isDelete", false);
        queryWrapper.like(StringUtils.isNotBlank(name), "name", name).or().like(StringUtils.isNotBlank(goal), "goal", goal).or().like(StringUtils.isNotBlank(chartType), "chartType", chartType);
        queryWrapper.orderByDesc("createTime");

        Page<Chart> chartPage = this.page(new Page<>(current, size), queryWrapper);

        return chartPage;
    }

    /**
     * 获取当前登录用户的图表分析信息
     *
     * @param chartQueryRequest
     * @param request
     * @return
     */
    @Override
    public Page<Chart> listMyChartByPage(ChartQueryRequest chartQueryRequest, HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        chartQueryRequest.setUserId(loginUser.getId());
        long current = chartQueryRequest.getCurrent();
        long size = chartQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<Chart> chartPage = this.page(new Page<>(current, size), ChartQueryWrapperUtils.getQueryWrapper(chartQueryRequest,loginUser));
        return chartPage;
    }


    /**
     * 返回当前用户的图表状态和图表数据 图表分析目标 图表名
     *
     * @param request
     * @return
     */
    @Override
    public List<ChartVO> getChartStatusList(HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        if (loginUser == null) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "用户未登录");
        }
        final int chartDataSize = 100000; //保证获取到最大页
        QueryWrapper<Chart> queryWrapper = new QueryWrapper<>();
        Long id = loginUser.getId();
        queryWrapper.eq(ObjectUtils.isNotEmpty(id), "userId", id);
        queryWrapper.eq("isDelete", false);
        Page<Chart> page = this.page(new Page<>(1, chartDataSize), queryWrapper);
        List<Chart> pageRecords = page.getRecords();
        List<ChartVO> chartStatusVOList = pageRecords.stream().map(chart -> {
            ChartVO chartStatusVO = new ChartVO();
            BeanUtils.copyProperties(chart, chartStatusVO);
            chartStatusVO.setUser(ConvertUtil.UserVOConvert(loginUser));
            return chartStatusVO;
        }).sorted(Comparator.comparing(ChartVO::getCreateTime).reversed()).collect(Collectors.toList());
        return chartStatusVOList;
    }

    /**
     * 编辑图表信息
     *
     * @param chartEditRequest
     * @param request
     * @return
     */
    @Override
    public Boolean editChart(ChartEditRequest chartEditRequest, HttpServletRequest request) {
        Chart chart = new Chart();
        BeanUtils.copyProperties(chartEditRequest, chart);
        User loginUser = userService.getLoginUser(request);
        long id = chartEditRequest.getId();
        // 判断是否存在
        Chart oldChart = this.getById(id);
        ThrowUtils.throwIf(oldChart == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if (!oldChart.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean result = this.updateById(chart);
        return result;
    }

    /**
     * 获取首页图表信息
     *
     * @param request
     * @return
     */
    @Override
    public ChartInfoVO getChartInfo(HttpServletRequest request) {
        try {
            User loginUser = userService.getUser(request);
            if (loginUser == null) {
                throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR, "用户未登录");
            }
            QueryWrapper<Chart> queryWrapper = new QueryWrapper<>();
            queryWrapper.orderByAsc("createTime");
            if (!ObjectUtil.equals(UserConstant.ADMIN_ROLE, loginUser.getUserRole())) {
                //如果不是管理员就只返回当前用户的数据
                queryWrapper.eq("userId", loginUser.getId());
            }
            List<Chart> chartList = this.list(queryWrapper);
            if (CollectionUtil.isEmpty(chartList)) {
                new ChartInfoVO(new ArrayList<>());
            }

            Map<Date, List<Chart>> chartMap = chartList.stream()
                    .collect(Collectors.groupingBy(obj -> {
                        Calendar cal = Calendar.getInstance();
                        cal.setTime(obj.getCreateTime());
                        cal.set(Calendar.HOUR_OF_DAY, 0);
                        cal.set(Calendar.MINUTE, 0);
                        cal.set(Calendar.SECOND, 0);
                        cal.set(Calendar.MILLISECOND, 0);
                        return cal.getTime();
                    }));

            List<Date> currentTimeList = new ArrayList<>(chartMap.keySet());
            List<Integer> countList = new ArrayList<>();

            Collections.sort(currentTimeList, new Comparator<Date>() {
                @Override
                public int compare(Date date1, Date date2) {
                    // 根据时间进行比较，时间越晚的排在前面
                    return date1.compareTo(date2);
                }
            });

            for (Date date : currentTimeList) {
                countList.add(chartMap.get(date).size());
            }

            ChartInfoVO chartInfoVO = new ChartInfoVO();
            chartInfoVO.setCallTimes(countList);
            chartInfoVO.setCurrentTime(currentTimeList);
            return chartInfoVO;
        } catch (Exception e) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR);
        }
    }


}




